<template>
  <el-form-item :label="config.label" :required="config.required">
    <div v-if="list && list.length" style="width: 100%">
      <el-table border :data="list">
        <el-table-column v-for="field in config.children" :label="field.label" :width="field.width">
          <template #default="scope">
            <field
              v-model="list[scope.$index][field.prop]"
              v-bind="{
                config: field,
                labelWidth: '0px',
                prop: `${field.prop}.${scope.$index}.${field.prop}`
              }"
            />
          </template>
        </el-table-column>
        <el-table-column fixed="right" width="180px" v-if="config?.props?.showBtn">
          <template #default="scope">
            <el-button text type="danger" @click="removeItem(scope.$index)">删除</el-button>
            <el-button text type="primary" @click="addItem(scope.$index)">添加</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-button v-else type="primary" plain @click="addItem(0)">添加{{ config.label }}</el-button>
  </el-form-item>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue';
import type { FieldType } from './type.d';
import Field from './field.vue';
const { config, modelValue } = defineProps<{
  config: FieldType;
  modelValue?: any[];
}>();
const emit = defineEmits(['update:modelValue']);
const checkDefaultValue = () => {
  if (modelValue) return modelValue;
  if (config.default) return config.default;
  return [];
};
const list = ref(checkDefaultValue());
watch(
  list,
  () => {
    emit('update:modelValue', list.value);
  },
  { immediate: true }
);
watch(
  () => modelValue,
  () => {
    list.value = modelValue;
  },
  { deep: true }
);

const addItem = i => {
  if (config.props.max) {
    if (list.value.length >= config.props.max) return;
  }
  if (!list.value) list.value = [];
  list.value.splice(i + 1, 0, {});
};

const removeItem = i => {
  if (config.props.min) {
    if (list.value.length <= config.props.min) return;
  }
  list.value.splice(i, 1);
};
</script>

<style lang="less" scoped>
.empty-box {
  margin: 20px 0;

  & > div {
    line-height: 1;
    margin-bottom: 10px;
  }
}
</style>
